package monocle.openinnitterpublic

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log

class MockActivity : PreferenceActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (intent?.action == Intent.ACTION_SEND) {
            if (intent.type == "text/plain") {
                intent.getStringExtra(Intent.EXTRA_TEXT)?.let {
                    startActivity(
                        Intent(
                            Intent.ACTION_VIEW,
                            it.replaceServices().toUri()
                        )
                    )
                }
            }
        }

        finish()
    }

    private fun String.replaceServices(): String {
        var res = this
        for (service in Service.values()) {
            res = res.replace(service.serviceToChange, this@MockActivity[service])
        }
        if (BuildConfig.DEBUG) {
            Log.d(MockActivity::class.java.simpleName, "$this → $res")
        }
        return res
    }
}

private fun String.toUri() = Uri.parse(
    if (startsWith("http://") || startsWith("https://")) this else "https://$this"
)